#include "threadpool.hpp"
#include "thread.hpp"
#include <unistd.h>
namespace moqi
{
Threadpool::Threadpool(int threadNUm, int queSize):
    _threads(),
    _threadNum(threadNUm),
    _queSize(queSize),
    _que(_queSize),
    _isExit(false)
    {

    }

Threadpool::~Threadpool()
{
    if(!_isExit)
        stop();
}

void Threadpool::start()
{
    for(int i = 0;i < _threadNum; ++i){
            unique_ptr<Thread> up(new Thread(bind(&Threadpool::doTask,this)));
        _threads.push_back(std::move(up));
    }
    
    for(auto &pthread:_threads){
        pthread->start();
    }

}

void Threadpool::stop()
{
    while(!_que.empty()){
        sleep(1);
    }

    _isExit = true;
    _que.wakeupAll();
    for(auto &pthread:_threads){
        pthread->join();
    }

}

void Threadpool::addTask(Taskfun && tcb)
{
    if(tcb)
        _que.push(std::move(tcb));
}

void Threadpool::doTask()
{
    while(!_isExit){
        Taskfun ptask = _que.pop();
        if(ptask){
            ptask();
        }
    }
}

}//end of namespace moqi
